<!-- 创建新企业 -->
<template>
  <div class="page-select-existing-enterprise page-next">
    <Form
      :model="formData.userRegisterNewCompanySaveVo"
      :rules="ruleValidate"
      ref="FormRef"
      label-position="top"
      @on-validate="formValidate"
    >
      <Row type="flex" justify="center" :gutter="20">
        <Col span="24">
          <h3 ref="companyBase">企业基本信息</h3>
        </Col>
        <Col span="12">
          <FormItem label="公司名称" prop="companyName">
            <Input
              v-model="formData.userRegisterNewCompanySaveVo.companyName"
              placeholder="请输入公司名称"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="证件类型" prop="companyCardTypeId">
            <Select
              v-model="formData.userRegisterNewCompanySaveVo.companyCardTypeId"
              placeholder="请选择证件类型"
            >
              <Option
                v-for="item in companyCard"
                :value="item.dictId"
                :key="item.dictId"
                >{{ item.name }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="证件号码" prop="companyCardNumber">
            <Input
              v-model="formData.userRegisterNewCompanySaveVo.companyCardNumber"
              placeholder="请输入证件号码"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="注册地址" prop="companyAddress">
            <Input
              v-model="formData.userRegisterNewCompanySaveVo.companyAddress"
              placeholder="请输入注册地址"
            ></Input>
          </FormItem>
        </Col>
        <Col span="24">
          <FormItem label="上传证件照片" prop="companyCardFile">
            <ViewImageList
              v-if="
                formData.userRegisterNewCompanySaveVo.companyCardFile.fileId
              "
              :echoFile="[
                formData.userRegisterNewCompanySaveVo.companyCardFile,
              ]"
              @delImge="delPhotoImge"
            />
            <UploadDrag v-else @uploadSuccess="uploadPhotoSuccess" />
          </FormItem>
        </Col>
        <Col span="24">
          <FormItem label="业务范围">
            <Input
              v-model="formData.userRegisterNewCompanySaveVo.businessRange"
              type="textarea"
              :rows="5"
              placeholder="请输入业务范围"
              class="auto-textarea"
            ></Input>
          </FormItem>
        </Col>
        <Col span="24">
          <FormItem label="关联上级组织">
            <CheckCompany
              :parentCompanyId.sync="
                formData.userRegisterNewCompanySaveVo.parentCompanyId
              "
            />
            <!-- <div class="select-company">
              <Select
                v-model="formData.userRegisterNewCompanySaveVo.companyServiceId"
                style="width: 200px"
                placeholder="请选择产业"
                @on-change="serviceChange"
              >
                <Option
                  v-for="item in companyService"
                  :value="item.dictId"
                  :key="item.dictId"
                  >{{ item.name }}</Option
                >
              </Select>
              <Select
                v-model="formData.userRegisterNewCompanySaveVo.parentCompanyId"
                filterable
                placeholder="请选择企业"
              >
                <Option
                  v-for="item in companyList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </div> -->
          </FormItem>
        </Col>
        <Divider />
        <Col span="24">
          <h3 ref="companyService">企业服务能力</h3>
        </Col>
        <Col span="24">
          <FormItem label="产业标记" prop="companyServiceTypeList">
            <CheckboxGroup v-model="companyServiceTypeList">
              <Checkbox
                :label="item.dictId"
                v-for="item in companyService"
                :key="item.dictId"
                >{{ item.name }}</Checkbox
              >
            </CheckboxGroup>
          </FormItem>
        </Col>
        <!-- <Col span="24">
          <h3>服务地区</h3>
        </Col> -->
        <Col span="24">
          <FormItem label="服务地区" prop="companyServiceAreaList">
            <Row :gutter="20">
              <Col span="24">
                <div
                  class="select-city"
                  v-for="(item, index) in areaList"
                  :key="item.id"
                >
                  <Select
                    v-model="item.provinceValue"
                    style="width: 200px; margin-right: 20px"
                    placeholder="请选择省份"
                    clearable
                    @on-change="provinceChange(item.provinceValue, index)"
                  >
                    <Option
                      v-for="item in provinceList"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.name }}</Option
                    >
                  </Select>
                  <Select
                    v-model="item.cityValue"
                    clearable
                    placeholder="请选择市"
                  >
                    <Option
                      v-for="(item, index) in item.cityList"
                      :value="item.id"
                      :key="index"
                      >{{ item.name }}</Option
                    >
                  </Select>
                  <div class="action-btn">
                    <span
                      @click="addCity(index)"
                      v-if="areaList.length == index + 1"
                      ><Icon
                        type="md-add-circle"
                        color="#0052d9"
                        :size="20"
                      /><i>添加</i></span
                    >
                    <span @click="delCity(index)" v-if="areaList.length > 1"
                      ><Icon
                        type="md-remove-circle"
                        color="#f00"
                        :size="20"
                      /><i>删除</i></span
                    >
                  </div>
                </div>
              </Col>
            </Row>
          </FormItem>
        </Col>
        <Col span="24">
          <h3>企业资质</h3>
        </Col>
        <Col span="24">
          <FormItem label="上传资质（选填）">
            <UploadAptitude
              ref="UploadAptitude"
              @handleOk="handleAction"
              @handleUpdetaOk="handleUpdetaOk"
            >
              <div
                class="update-photo-btn"
                v-if="
                  formData.userRegisterNewCompanySaveVo.companyAptitudeList
                    .length
                "
              >
                <BtnBox iconName="icon_3" boxWidth="96" text="点击添加" />
              </div>
              <div class="update-photo" v-else>点击添加</div>
            </UploadAptitude>
            <div
              class="aptitude-list"
              v-if="
                formData.userRegisterNewCompanySaveVo.companyAptitudeList.length
              "
            >
              <Table
                :columns="columns"
                :data="
                  formData.userRegisterNewCompanySaveVo.companyAptitudeList
                "
              >
                <template slot-scope="{ row, index }" slot="ImgAction">
                  <ViewImageList
                    v-if="row.fileVo.fileId"
                    isViewBtn
                    :echoFile="[row.fileVo]"
                  />
                </template>
                <template slot-scope="{ row, index }" slot="action">
                  <BtnText
                    type="primary"
                    @BtnClick="editAptitude(row, 1, index)"
                    >修改</BtnText
                  >
                  <BtnText type="error" @BtnClick="editAptitude(row, 2, index)"
                    >删除</BtnText
                  >
                </template>
              </Table>
            </div>
          </FormItem>
        </Col>
        <Col span="24">
          <h3>企业收益规则</h3>
        </Col>
        <Col span="12">
          <FormItem label="收益规则">
            <InputNumber
              style="width: 100%"
              v-model="
                formData.userRegisterNewCompanySaveVo.companyDivideIntoRuleValue
              "
              placeholder="请输入分层规则"
            />
          </FormItem>
        </Col>
        <Col span="12"></Col>
        <Col span="24">
          <FormItem label="上传规则说明">
            <ViewImageList
              v-if="
                formData.userRegisterNewCompanySaveVo.companyDivideIntoRuleFile
                  .fileId
              "
              :echoFile="[
                formData.userRegisterNewCompanySaveVo.companyDivideIntoRuleFile,
              ]"
              @delImge="delDivideIntoRuleFile"
            />
            <UploadDrag
              v-else
              @uploadSuccess="uploadDivideIntoRuleFileSuccess"
            />
          </FormItem>
        </Col>
        <Col span="16">
          <div class="next-btn">
            <Button
              type="primary"
              :disabled="isBtnDisabled"
              :loading="isLoading"
              @click="handleAgree"
              >确认创建企业并完成注册</Button
            >
          </div>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import {
  GetNationAreaByParentId,
  GetDict, // 获取证件类型
  // RegisterGetCompanyList, // 获取上级组织
  GetCompanySelectByCompanyService, // 根据产业标记获取组织
} from "@/api/common.js";

import { UserAndCompanyRegister } from "@/api/account.js";

import UploadAptitude from "@/pages/account/register/components/uploadAptitude.vue";
import CheckCompany from "@/pages/account/register/components/checkCompany.vue";
import { encrypt } from "@/utils/encrypFile";
export default {
  components: {
    UploadAptitude,
    CheckCompany,
  },
  data() {
    const validateCompanyCardFile = (rule, value, callback) => {
      if (!this.formData.userRegisterNewCompanySaveVo.companyCardFile.fileId) {
        callback(new Error("请上传证件照片"));
      } else {
        callback();
      }
    };

    const validateCompanyServiceType = (rule, value, callback) => {
      if (this.companyServiceTypeList.length) {
        callback();
      } else {
        callback(new Error("请选择产业标记！"));
      }
    };

    const validateCompanyProvince = (rule, value, callback) => {
      if (this.areaList.length) {
        for (let item in this.areaList) {
          let provinceValue = this.areaList[item].provinceValue;
          let cityValue = this.areaList[item].cityValue;
          let lenP = this.areaList.filter(
            (o) => o.provinceValue == provinceValue && o.cityValue == cityValue
          ).length;
          if (lenP > 1) {
            callback(new Error("选择地区重复！"));
            break
          }
          // if (!this.areaList[item].cityValue) {
          //   callback(new Error("请选择服务城市！"));
          // }
          if (!this.areaList[item].provinceValue) {
            callback(new Error("请选择服务省份！"));
          }
        }
        callback();
      } else {
        callback(new Error("请选择服务地区！"));
      }
    };

    return {
      isBtnDisabled: false,
      modelValue: "",
      isHide: false,
      areaList: [
        {
          id: "",
          provinceValue: "",
          cityValue: "1",
          cityList: [],
        },
      ],
      provinceList: [],
      formData: {
        isRegisterNewCompany: true, // 是否注册公司
        joinCompanyId: "",
        userRegisterNewCompanySaveVo: {
          // 注册新公司基本信息
          companyName: "", // 新公司名称
          companyCardTypeId: "",
          companyCardTypeName: "", // 营业执照
          companyCardNumber: "", // 营业执照编号
          companyAddress: "", // 注册地址
          companyCardFile: [], // 证件图片
          businessRange: "", // 经营范围
          parentCompanyId: "", // 上级公司ID\
          parentCompanyName: "", // 上级公司名称
          companyServiceTypeList: [], // 公司服务类型
          companyServiceAreaList: [], // 企业地址
          companyAptitudeList: [], // 企业资质
          companyDivideIntoRuleValue: 0, // 收益规则
          companyDivideIntoRuleFile: {}, // 收益规则文件
        },
      },
      ruleValidate: {
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "change" },
        ],
        companyCardTypeName: [
          { required: true, message: "请选择证件类型", trigger: "change" },
        ],
        companyCardNumber: [
          { required: true, message: "请输入证件号码", trigger: "change" },
        ],
        companyAddress: [
          { required: true, message: "请输入注册地址", trigger: "change" },
        ],
        companyCardFile: [
          // { required: true, message: "请上传证件照片", trigger: "change" },
          {
            required: true,
            validator: validateCompanyCardFile,
            trigger: "change",
          },
        ],
        companyServiceTypeList: [
          {
            required: true,
            validator: validateCompanyServiceType,
            message: "请选择产业标记",
            trigger: "change",
          },
        ],
        companyServiceAreaList: [
          {
            required: true,
            validator: validateCompanyProvince,
            trigger: "blur",
          },
        ],
      },
      docType: [], // 证件类型
      docType: [],
      parentCompanyList: [], // 上级产业
      companyList: [],
      companyService: [], // 公司服务能力
      companyCard: [], // 证件类型
      columns: [
        {
          title: "资质名称",
          key: "companyAptitudeName",
        },
        {
          title: "等级",
          key: "lv",
        },
        {
          title: "资质附件",
          slot: "ImgAction",
        },
        {
          title: "有效期截至日期",
          key: "validEndDate",
        },
        {
          title: "操作",
          slot: "action",
        },
      ],
      currentIndex: 0,
      companyServiceTypeList: [],
      isLoading: false,
      baseTop: 0,
      setviceTop: 0,
      isTop: 0,
      isVerify: false,
    };
  },
  methods: {
    async getNationAreaData(dataKey, params = {}) {
      let data = await GetNationAreaByParentId(params);
      console.log(data, "data123");
      if (dataKey == "provinceList") {
        this.provinceList = data;
      }
      if (dataKey == "cityList") {
        let resData = [
          {
            id: "1",
            name: "全部",
          },
        ].concat(data);
        this.areaList[params.index].cityList = resData;
      }
    },
    async getDictData(key, name) {
      let data = await GetDict({
        parentId: key,
      });
      this[name] = data;
      console.log(data, "data");
    },
    // 获取上级组织
    async getCompanySelectByCompanyServiceData(companyServiceTypeId) {
      let params = {
        companyServiceTypeId,
      };
      let data = await GetCompanySelectByCompanyService(params);
    },

    // 切换省市
    provinceChange(parentId, index) {
      let params = {};
      if (parentId) {
        params = {
          parentId,
          index,
        };
      }
      this.areaList[index].cityValue = "1";
      this.getNationAreaData("cityList", params);
    },
    // cityChange(ev,item){
    //   console.log(ev,item,'132')
    //   if(!ev){
    //     item.cityValue = "1"
    //   }
    // },
    addCity() {
      this.areaList.push({
        id: Date.now(),
        provinceValue: "",
        cityValue: "1",
        cityList: [],
      });
    },
    delCity(index) {
      this.areaList.splice(index, 1);
    },
    uploadPhotoSuccess(file) {
      this.formData.userRegisterNewCompanySaveVo.companyCardFile = file;
      this.$refs["FormRef"].validateField("companyCardFile");
    },
    handleUpdetaOk(item) {
      console.log(item, "2", this.currentIndex);
      this.formData.userRegisterNewCompanySaveVo.companyAptitudeList[
        this.currentIndex
      ] = item;
    },
    // 删除照片
    delPhotoImge(index) {
      this.formData.userRegisterNewCompanySaveVo.companyCardFile = {};
      this.$refs["FormRef"].validateField("companyCardFile");
    },
    // 添加企业资质
    handleAction(item) {
      this.formData.userRegisterNewCompanySaveVo.companyAptitudeList.push(item);
    },
    // 新增修改资质
    editAptitude(item, type, index) {
      // 修改
      if (type == 1) {
        this.currentIndex = index;
        this.$refs.UploadAptitude.showModal(item);
      }
      // 删除
      if (type == 2) {
        this.formData.userRegisterNewCompanySaveVo.companyAptitudeList.splice(
          index,
          1
        );
      }
    },
    // 删除分层规则文件
    delDivideIntoRuleFile(index) {
      this.formData.userRegisterNewCompanySaveVo.companyDivideIntoRuleFile.splice(
        index,
        1
      );
    },
    // 添加分层规则文件
    uploadDivideIntoRuleFileSuccess(item) {
      this.formData.userRegisterNewCompanySaveVo.companyDivideIntoRuleFile =
        item;
    },

    // 选择企业
    serviceChange(value) {
      // 获取企业
      this.getCompanySelectByCompanyServiceData(value);
    },
    formValidate(prop, status, error) {
      let companyBase = [
        "companyName",
        "companyCardTypeName",
        "companyCardNumber",
        "companyAddress",
        "companyCardFile",
      ];
      let companyService = ["companyServiceTypeList", "companyServiceAreaList"];
      if (error && this.isTop == 0) {
        this.$Message.error(error);
      }
      if (companyBase.includes(prop) && !status && this.isVerify) {
        this.isTop = 1;
        this.isVerify = false;
        this.$emit("updateScroll", this.baseTop);
        return;
      }
      if (
        companyService.includes(prop) &&
        !status &&
        this.isVerify &&
        this.isTop == 0
      ) {
        this.isVerify = false;
        this.$emit("updateScroll", this.setviceTop);
        return;
      }
    },
    handleAgree() {
      console.log(11, JSON.parse(localStorage.getItem("registerBaseData")));
      this.isTop = 0;
      this.isVerify = true;
      this.$refs["FormRef"].validate(async (valid) => {
        if (valid) {
          let userBase = JSON.parse(localStorage.getItem("registerBaseData"));
          userBase.pwd = encrypt(userBase.pwd);
          userBase.confirmPwd = encrypt(userBase.confirmPwd);
          this.formData.userRegisterNewCompanySaveVo.companyServiceTypeList =
            this.companyServiceTypeList.map((o) => {
              return {
                serviceTypeId: o,
              };
            });

          this.formData.userRegisterNewCompanySaveVo.companyServiceAreaList =
            this.areaList.map((o) => {
              return {
                provinceCode: o.provinceValue,
                cityCode: o.cityValue == "1" ? "" : o.cityValue,
              };
            });
          let params = {
            ...userBase,
            ...this.formData,
          };
          this.isLoading = true;
          try {
            let data = await UserAndCompanyRegister(params);
            this.isLoading = false;
            this.$emit("handleSuccess", this.formData);
          } catch (error) {
            this.isLoading = false;
          }
        } else {
          // this.$Message.error("信息验证不通过");
        }
      });
    },
    // 初始化请求接口
    bsaeApi() {
      this.getNationAreaData("provinceList", {}); // 获取省市区
      this.getDictData("COMPANY_CARD_TYPE", "companyCard"); // 获取证件类型
      this.getDictData("COMPANY_SERVICE", "companyService"); // 获取公司服务能力
    },
  },
  created() {},
  mounted() {
    this.bsaeApi();
    this.baseTop = this.$refs.companyBase.getBoundingClientRect().top;
    this.setviceTop = this.$refs.companyService.getBoundingClientRect().top;
  },
};
</script>

<style lang="less" scoped>
.page-select-existing-enterprise {
  h3 {
    font-size: 18px;
    margin: 20px 0;
  }
}

.select-company {
  display: flex;
  border: 1px solid #c4c4c4;
  border-radius: 4px;
  ::v-deep(.ivu-select-selection) {
    border: none;
  }
}

.select-company-item {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  margin-top: 20px;
  border: 1px solid #c4c4c4;
  border-radius: 4px;
}
.next-btn {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
.ivu-btn {
  width: 100%;
}

.select-city {
  display: flex;
  position: relative;
  margin-bottom: 20px;
  .action-btn {
    position: absolute;
    right: 0;
    transform: translateX(100%);
    height: 100%;
    display: flex;
    align-items: center;
    span {
      display: flex;
      margin-left: 10px;
      cursor: pointer;
      align-items: center;
      i {
        font-style: normal;
        margin-left: 5px;
      }
    }
  }
}
.ivu-input,
.ivu-select-selection {
  background: #fff;
}

.update-photo {
  text-align: center;
  background: #eee;
  border-radius: 2px;
  flex: none;
  height: 80px;
  line-height: 80px;
  width: 100%;
  cursor: pointer;
}

.aptitude-list {
  margin-top: 15px;
}
</style>
